package dhz.storage.configurations;

import dhz.storage.models.UploadTask;
import dhz.storage.util.BeanUtil;
import dhz.storage.util.UploadTaskRedisUtil;
import net.bytebuddy.dynamic.scaffold.MethodGraph;
import org.apache.commons.fileupload.ProgressListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

public class CustomUploadListener implements ProgressListener {
    static final Logger logger = LoggerFactory.getLogger(CustomUploadListener.class);

    UploadTaskRedisUtil util;

    // 这个listener在监听哪个用户的上传任务
    private String userID;

    // 这个listener监听的任务的id是什么
    private String taskID;

    /**
     * 新建一个任务监听器
     * @param user_id 用户的id是通过jwt解析出来的用户的学号
     * @param taskName 上传文件的名字
     * */
    public CustomUploadListener(String user_id, String taskName){
        util = BeanUtil.getBean(UploadTaskRedisUtil.class);
        this.userID = user_id;
        taskID = ""+Calendar.getInstance().getTimeInMillis()+(new Random().nextInt()%10000);
        UploadTask t = new UploadTask();
        t.setName(taskName);
        util.addUploadTask(this.userID, this.taskID, t);
        logger.info("task: "+this.taskID+" of user: "+this.userID+" has been established");
    }

    @Override
    public void update(long finishedByte, long totalByte, int index) {
        util.updateTask(this.userID, this.taskID, finishedByte, totalByte);
    }

    /**
     * 关闭监听器，把相关的任务删除掉
     * */
    public void close(){
        util.deleteTask(userID, taskID);
    }
}
